package androtv.md;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
import androtv.models.News;
import androtv.utils.JSONSerializatorUtil;
import androtv.utils.SiteClientUtil;

public class AndrotvmdActivity extends Activity {
	private ArrayList<News> _news;
	private int _index;
	private int _len;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    	try {
    		
	    	String jsonNews = SiteClientUtil.getNews();  
	    	_news = JSONSerializatorUtil.Derialize(jsonNews);
	    	_index = 0 ;
	    	_len = _news.size();
	    	
    	} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public void onButton1_Click(View view){
    		if(_index == _len){
    			_index = 0;
    		}
    		
    		News  news = _news.get(_index++);

			TextView tView = (TextView)findViewById(R.id.textView1);
			tView.setText(news.description);

			TextView tileView = (TextView)findViewById(R.id.textViewTitle);
			tileView.setText(news.title);
			
			ImageView iView = (ImageView)findViewById(R.id.imageView1);
			try {
				iView.setImageBitmap(SiteClientUtil.getImage(news.imageUrl));
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
    
    public void onbtnShowVid_Click(View view){
    	
    	String videoUrl;
		try {
			videoUrl = SiteClientUtil.getVideoUrl(_news.get(_index - 1).link);
			if(videoUrl == null){
				return;
			}
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(videoUrl), "video/*");
			startActivity(intent);
			
			/*setContentView(R.layout.video);
			videoUrl = SiteClientUtil.getVideoUrl(_news.get(_index).link);
			VideoView videoView = (VideoView) findViewById(R.id.videoViewMain);
			MediaController mediaController = new MediaController(this);
			mediaController.setAnchorView(videoView);
			mediaController.setMediaPlayer(videoView);
			videoView.setMediaController(mediaController);
			videoView.requestFocus();
			Uri uri = Uri.parse(videoUrl);
			videoView.setVideoURI(uri);
		
			/*videoView.setOnPreparedListener(new OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                     videoView.start();
                }
            });*/
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
  }